var express = require('express');
var http = require('http');
var gm = require('gm');
var ejs = require("ejs");
var async = require('asyncawait/async');
var await = require('asyncawait/await');
var fs = require('fs');
var app = express();
app.engine('.html', ejs.__express);
app.set('view engine', 'html');

app.use(express.static(__dirname + '/public'));
app.use('/views', express.static(__dirname+'/views'));

app.get('/', (req, res) => {
    res.render('index');
});


/**
 * async/await 是目前最简单处理异步的方案了
 * 
 * 就是将异步转变成同步。
 * 
 * 规则：
 *  1、async表示这是一个async函数，await只能在这个函数中使用。
 *  2、await表示在这里等待promise返回结果了，在继续执行
 *  3、await 后面跟着的应该是一个promise对象
 */

app.post('/index', (req, res) => {
    req.setTimeout(6000000, function () {
        console.log("请求超时。");
    });
    res.setTimeout(600000000,function(){
        console.log("响应超时.");
    });

    (async(
        function () {
            var url = 'E:/picture';
            var newu = 'E:/readfile/public/static';
            var allPicture = fs.readdirSync(url);
            for (var i = 0; i < allPicture.length; i++) {
                if (allPicture[i].indexOf('.JPG') > 0) {
                    await(copyImg(url + '/' + allPicture[i], newu + '/' + allPicture[i]));
                    await(cutImg(url + '/' + allPicture[i], newu + '/cut' + allPicture[i]));
                    // 两个函数同时执行
                    // await Promise.all([copyImg('first', 'second'), cutImg('first', 'second')]);
                }
            }
            console.log('图片处理完成');
            res.send('success');
        }
    ))();
});


// 复制文件
function copyImg (sourceP, newP) {
    return new Promise((resolve, reject) => {
        var readStream = fs.createReadStream(sourceP);
        var writeStream = fs.createWriteStream(newP);
        readStream.on('data', (data) => {
            writeStream.write(data);
        });

        readStream.on('end', () => {
            console.log('readStream end');
            writeStream.end();
            resolve();
        });
    });
}

// 缩略图
function cutImg (sourceP, newP) {
    return new Promise((resolve, reject) => {
        var readStream = fs.createReadStream(sourceP);
        gm(readStream).size({bufferStream: true}, function(err, size) {
            this.resize(100, 150);
            this.write(newP, function (err) {
                if (!err) {
                    console.log('done');
                    resolve();
                } else {
                    throw err;
                }
            });
        });
    });
}

http.createServer(app).listen(3000, () => {
    console.log('server posrt is 3000');
});